/**
 * Created by Jie on 2017/2/4.
 */
var async = require('async');
var db = require('../../util/pool');
var format = require('../../util/json2sql');
var _ = require('underscore');
var data = require('../../util/result');

var Model = function() {};
var _table = 'users';
//通过用户名获取数据
Model.prototype.findByUserName = function(userName, callback) {
    var sql = "SELECT id,roleId,userName,password,salt,status,trueName FROM users WHERE isDel =0 and userName='"+userName+"'";
    db.queryFirst(sql,function (err,results) {
        if(!err){
            callback(null,results);
        }
    })
};
//检查用户名是否存在
Model.prototype.checkUserName = function (_where,callback) {
    var sql = format.check(_table,_where);
    db.queryFirst(sql,function (err,result) {
        if(!err){
            callback(null,result);
        }
    })
}
//通过id获取数据
Model.prototype.one = function (_id,callback) {
    var sql = format.one(_table,_id);
    db.queryFirst(sql,function (err,results) {
        if(!err){
            callback(null,results);
        }
    })
}
//添加数据
Model.prototype.insert = function(json, callback) {
    var sql = format.insert(_table,json);
    db.exec(sql,function (err,results) {
        if(!err){
            callback(null,results);
        }
    });
};
//编辑数据
Model.prototype.edit = function (json,callback) {
    var sql = format.update(_table,json);
    db.exec(sql,function (err,results) {
        if(!err){
            callback(null,results);
        }
    })
}
//删除数据
Model.prototype.del = function (params,callback) {
    var sql = format.delete(_table,params)
    db.exec(sql,function (err,results) {
        if(!err){
            callback(null,results);
        }
    })
}
//数据列表
Model.prototype.list = function(where, callback) {
    var countSql = format.count(_table,where);
    var dataSql = '';
    var idsSql = format.ids(_table,where);
    var result = {};
    async.waterfall([
        function(callback) {
            db.queryFirst(countSql,function (err,results) {
                if(!err){
                    result.total = results.rows;
                    callback(null,results);
                }
            });
        },
        function(onearg, callback) {
            db.query(idsSql,function (err,results) {
                if(!err){
                    callback(null,results);
                }
            });
        },
        function(twoarg, callback) {
            var ids = [];
            for(var i=0;i<twoarg.length;i++){
                ids.push(twoarg[i].id);
            }
            dataSql = format.select(_table,where,ids.join(','));
            db.query(dataSql,function (err,results) {
                if(!err){
                    result.error = 0;
                    result.data = results;
                    callback(null,result);
                }
            });
        },
        function (users,callback) {
            var userList = users.data;
            var _cond = {where:'',order:' id desc'};
            var bmSql = format.all('department',_cond.where,_cond.order);
            db.query(bmSql,function (err,results) {
                if(!err){
                    for(var i=0;i<userList.length;i++){
                        userList[i].departmentName = getDepartmentNameById(userList[i].departmentId,results);
                    }
                    users.data = userList;
                    callback(null,users);
                }

            })
        },
        function (vals,callback) {
            var users = vals.data;
            var _cond = {where:'',order:' id desc'};
            var roleSql = format.all('role',_cond.where,_cond.order);
            db.query(roleSql,function (err,results) {
                if(!err){
                    for(var i=0;i<users.length;i++){
                        users[i].roleName = getDepartmentNameById(users[i].roleId,results);
                    }
                    vals.data = users;
                }

                callback(null,vals);
            })
        }
    ], function(error, result) {
        callback(null, result);
    });
};
//重置密码
Model.prototype.init = function (json,callback) {
    var sql = "update users set password='"+json.password+"',salt='"+json.salt+"' where id="+json.id;
    db.exec(sql,function (err,results) {
        if(!err){
            callback(null,results);
        }
    })
}
//in查询
Model.prototype.findByIds = function (_ids,callback) {
    var sql = format.findIn(_table,_ids);
    db.query(sql,function (err,results) {
        if(!err){
            callback(null,data.result(0,'ok',results));
        }else{
            callback(null,data.result(1,'异常'));
        }
    })
}

function getDepartmentNameById(_id,_list) {
    var name = '未知';
    for(var key in _list){
        var department = _list[key];
        if(department.id == _id){
            name = department.name;
            break;
        }
    }
    return name;
}
function getRoleNameByRoleId(_id,_list) {
    var name = '未知';
    for(var key in _list){
        var role = _list[key];
        if(role.id == _id){
            name = role.name;
            break;
        }
    }
    return name;
}

module.exports = Model;